<!--
 * @Descripttion:
 * @version:
 * @Author: tanghao1
 * @Date: 2021-02-20 14:06:05
 * @LastEditors: tanghao1
 * @LastEditTime: 2021-07-13 08:52:11
-->
<template>
  <div>
    <div class="nav-head">
      <el-row type="flex" class="row-bg" flex-direction="row-reverse">
        <el-col :span="4"><div><span>基础信息</span></div></el-col>
        <el-col :span="16" />
        <el-col :span="4">
          <el-button size="mini" @click="addcancel">取消</el-button>
          <el-button type="primary" size="mini" @click="submitForm">保存</el-button>
        </el-col>
      </el-row>
      <el-form ref="form" :model="formData" :rules="formRules" size="mini" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图册名称" prop="atlasName" :rules="atlasName">
              <el-input v-model="formData.atlasName" size="mini" placeholder="请输入图册名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否显示" prop="state">
              <el-switch
                v-model="formData.state"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传封面" prop="uplodaFile">
              <el-upload
                class="avatar-uploader"
                :headers="headers"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="imgUrl" :src="imgUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row></el-form>
      <el-row type="flex" class="row-bg" flex-direction="row-reverse">
        <el-col :span="4"><div><span>属性信息</span></div></el-col>
      </el-row>
      <el-row type="flex" class="row-bg" flex-direction="row-reverse">
        <el-col :span="4">
          <el-button size="mini" type="primary" @click="add">新增</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        row-key="id"
      >
        <el-table-column
          prop="attName"
          label="属性名称"
          sortable
          width="300"
        />
        <el-table-column label="属性值">
          <template v-slot="{row,$index}">
            <el-select
              v-if="modelIndex === $index"
              v-model="row.item"
              size="mini"
              placeholder="请选择"
              :rules="gotoType"
            >
              <el-option
                v-for="item in attrValueList"
                :key="item.id"
                :label="item.fixedName"
                :value="item.fixedName"
              />
            </el-select>

            <!-- <el-select
              v-if="modelIndex === $index"
              v-model="row.item"
              size="mini"
              placeholder="请选择"
              :rules="gotoType"
              @change="getSelectData(data)"
            >
              <el-option
                v-for="item in attrValueList"
                :key="item.id"
                :label="item.fixedName"
                :value="{fixedCode:item.fixedCode,fixedName:item.fixedName}"
              />
            </el-select> -->
            <span v-else>
              <span v-if="row.item">{{ row.item || row.fixedName }}</span>
              <span v-else>{{ row.item || row.fixedName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row,$index}">
            <el-button v-if="!isShowEdit" type="text" size="mini" @click="handleCancel(row,$index)">取消</el-button>
            <el-button v-if="!isShowEdit" type="text" size="mini" @click="saveThree(row,$index)">保存</el-button>
            <el-button v-if="isShowEdit" type="text" size="mini" @click="handleDel(row,$index)">删除</el-button>
            <el-button v-if="isShowEdit" type="text" size="mini" @click="addnavThree(row,$index)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <add-three v-if="showThree" ref="formthree" :visible.sync="showThree" :detail-data="detailData" :other-filter="otherFilter" @refreshTablethree="refreshTablethree" @getChildData="getChildData" />
  </div>
</template>

<script>
import AddThree from './AddThree'
import { getToken } from '@/utils/auth'
import { editAtlas, getByAtlasAttributeId } from '@/api/shopauxPlat/atlasManagement'
export default {
  name: 'AddFormson',
  components: { AddThree },
  props: {
    detailDataThree: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      showEdit: false,
      showThree: false,
      isShowEdit: true,
      modelIndex: '',
      imgUrl: '',
      uploadUrl: `${process.env.VUE_APP_BASE_API}/api/v1/file/upload`,
      headers: {
        'X-Token': this.$store.getters.token ? getToken() : '',
        'Authorization': this.$store.getters.token ? 'Bearer ' + getToken() : ''
      },
      submiting: false,
      attCodeList: [],
      attNameEmpty: [],
      isEmpty: false,
      picFile: [],
      otherFilter: [],
      attrValueList: [],
      pricingTypeCodeList: [], // 因子类型
      formData: {
        atlasName: '',
        state: '1',
        detailData: []
      },
      detailData: [],
      tableData: [],
      formRules: {
        atlasName: [{
          required: true,
          message: '请输入图册名称',
          trigger: 'blur'
        }],
        state: [{
          required: true,
          message: '请选择是否显示',
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {},
  watch: {
    'tableData': {
      handler(val, oldVal) {
        console.log(999)
        this.attrValueList.forEach(item => {
          val.forEach(itmeval => {
            if (itmeval.item === item.fixedName) {
              this.attCodeList.push({ attCode: item.fixedCode, attName: item.fixedName })
            }
          })
        })
      }
    }
  },
  created() {
    const data = this.detailDataThree
    console.log(this.detailDataThree)
    if (data.state === 1) {
      data.state = '1'
    }
    if (data) {
      this.formData = this.detailDataThree
      this.tableData = this.formData.attributeList
      this.imgUrl = this.formData.picUrl
    }
  },
  methods: {
    getSelectData(data) {
      console.log(data)
    },
    handleAvatarSuccess(res, file) {
      this.picFile = file.response.data
      this.imgUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      console.log(file)
      const isLt2M = file.size / 1024 / 1024 < 5
      const isJPG = file.type.split('/')[1]
      const allowPic = ['jpg', 'png', 'jpeg']
      if (!allowPic.includes(isJPG)) {
        this.$message.error('上传图片只能是 png/jpg 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    closeDialog() {
      this.dialogShow = false
    },
    addcancel() {
      this.$emit('refreshTablethree')
    },
    add() {
      this.getOtherFilter(this.tableData)
      this.showThree = true
    },
    // 提交表单处理
    submitForm() {
      //  判断属性是否选择
      if (this.tableData.length === 0) {
        this.$message.warning('请至少添加一条属性信息')
        return
      }
      this.tableData.forEach(item => {
        if (!item.attributeId && !item.item) {
          this.attNameEmpty.push(item.attName)
          this.isEmpty = true
        }
      })
      if (this.isEmpty) {
        this.$message.warning(this.attNameEmpty + '的属性值必选!')
        this.attNameEmpty = []
        this.isEmpty = !this.isEmpty
        return
      }
      const data = {}
      data.atlasName = this.formData.atlasName // 图册名称
      data.picName = this.formData.picName // 图册封面名称
      data.picUrl = this.picFile.url// 图册封面地址
      if (this.formData.state === '1') { // 是否显示
        data.state = 1
      } else {
        data.state = 0
      }
      data.id = this.formData.id
      data.levelType = this.formData.levelType
      const attributeList = [] // 属性信息
      console.log(this.tableData)
      this.tableData.forEach((item, index) => {
        attributeList[index] = {}
        attributeList[index].attCode = item.attCode
        attributeList[index].attName = item.attName
        attributeList[index].attributeId = item.id || item.attributeId
        if (item.item) {
          // attributeList[index].fixedCode = this.attCode[index]
          // attributeList[index].fixedName = item.item
          this.attCodeList.forEach(val => {
            console.log(val)
            console.log(item.item)
            if (val.attName === item.item) {
              attributeList[index].fixedCode = val.attCode
              attributeList[index].fixedName = val.attName
            }
          })
        } else {
          attributeList[index].fixedCode = item.fixedCode
          attributeList[index].fixedName = item.fixedName
        }
      })
      console.log(111)
      data.attributeList = attributeList
      editAtlas(data).then(res => {
        if (res.success === 1) {
          this.$message.success('保存成功')
          this.dialogShow = false
          this.$emit('refreshTablethree')
        }
      })
    },
    getChildData(data) {
      this.tableData = this.tableData.concat(data)
      console.log(this.isShowEdit)
      this.isShowEdit = true
      this.modelIndex = ''
      this.getOtherFilter(this.tableData)
    },
    // 删除
    handleDel(row, index) {
      this.tableData.splice(index, 1)
    },
    // 取消
    handleCancel(row, index) {
      if (this.modelIndex === index) {
        this.modelIndex = ''
        this.isShowEdit = !this.isShowEdit
      }
    },
    // 编辑
    addnavThree(data, index) {
      this.isShowEdit = !this.isShowEdit
      this.modelIndex = index
      const id = data.id || data.attributeId
      getByAtlasAttributeId(id).then(res => {
        if (res.success === 1) {
          this.attrValueList = res.data
        }
      })
    },
    saveThree(row, index) {
      console.log(this.modelIndex)
      console.log(index)
      if (this.modelIndex === index) {
        this.modelIndex = ''
        this.isShowEdit = !this.isShowEdit
      }
    },
    // 获取因子组合编码集合，作为弹框过滤条件
    getOtherFilter(data) {
      if (data && data.length > 0) {
        const attCode = data.map(item => item.attCode).join()
        this.otherFilter = [{ id: 'attCode', property: 'attCode', value: `[${attCode}]`, operator: 'not in' }]
      } else {
        this.otherFilter = []
      }
    }
  }
}
</script>
<style lang='scss' scoped>
 .nav-head{
   margin: 20px 0 20px 0;
 }
  .basicpic{
   width: 100px;
   height: 100px;
   margin: 5px;
 }
 .avatar-uploader .el-upload {
    border: 1px dashed #0c0202;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #0c0202;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
   .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  .row-bg{
    margin: 20px ;
  }
</style>

